#include "amimporter.h"
#include "stdlib.h"
#include "stdio.h"
#include "amutils.h"
#include <QtEndian>
#include <QMessageBox>


AMImporter::AMImporter(QObject *parent) : QObject(parent)
{
}

model * AMImporter::read(QString filename)
{
    FILE * fin = fopen(filename.toStdString().c_str(), "r");

    int vc, nc, ic;

    fread(&vc, sizeof(int), 1, fin);
    fread(&nc, sizeof(int), 1, fin);
    fread(&ic, sizeof(int), 1, fin);

    vc = qFromBigEndian(vc);
    nc = qFromBigEndian(nc);
    ic = qFromBigEndian(ic);

    float tempVerts [vc];
    float tempNorms [nc];
    short tempInds [ic];

    fread(tempVerts, sizeof(float), vc, fin);
    fread(tempNorms, sizeof(float), nc, fin);
    fread(tempInds, sizeof(short), ic, fin);

    model * result = (model *) malloc(sizeof(model));
    result->verts = (float *) malloc(sizeof(float) * vc);
    result->norms = (float *) malloc(sizeof(float) * nc);
    result->vinds = (short *) malloc(sizeof(short) * ic);
    result->ninds = (short *) malloc(sizeof(short) * ic);

    int index;
    for(int i = 0; i < ic; i++) {
        index = i*3;
        result->verts[index] = AMUtils::revEndian(tempVerts[index]);
        result->verts[index + 1] = AMUtils::revEndian(tempVerts[index + 1]);
        result->verts[index + 2] = AMUtils::revEndian(tempVerts[index + 2]);

        result->norms[index] = AMUtils::revEndian(tempNorms[index]);
        result->norms[index + 1] = AMUtils::revEndian(tempNorms[index + 1]);
        result->norms[index + 2] = AMUtils::revEndian(tempNorms[index + 2]);

        result->ninds[i] = result->vinds[i] = qFromBigEndian(tempInds[i]);
    }

    fclose(fin);

    emit(importComplete(result));

    return result;
}
